#include <iostream>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string>
#include <cstring>
#include <cerrno>
#include <unistd.h>

#include "err.hpp"

using namespace std;


int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        cout << "name [ip] [port]" << endl;
    }

    string serverip = argv[1];
    uint16_t serverport = atoi(argv[2]); 

    //1 create socket
    int sock = socket(AF_INET,SOCK_STREAM,0);
    if(sock < 0)
    {
        cerr << "create socket error" << endl;
        exit(SOCKED_ERR);
    }

    //2 connect
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    //这个安全
    inet_aton(serverip.c_str(),&server.sin_addr);

    int cnt = 5;
    while(connect(sock,(sockaddr*)&server,sizeof(server)) != 0)
    {
        sleep(1);
        cout << "正在重新连接，重连机会还有：" << cnt-- << endl;

        if(cnt <= 0) break;
    }
    if(cnt <= 0) 
    {
        cout << "重连失败，已经退出" << endl;
        exit(CONNECT_ERR);
    }

    //3 连接成功了
    char buffer[1024];
    while(true)
    {
        string line;
        cout << "Enter>>>";
        getline(cin,line);
        
        //write和read不是一个缓冲区，不会影响的
        write(sock,line.c_str(),line.size());

        ssize_t s = read(sock,buffer,sizeof(buffer)-1);
        if(s > 0)
        {
            buffer[s] = 0;
            cout << "server echo>>>" << buffer << endl;
        }
        else if(s == 0)
        {
            cerr << "server quit" << endl;
            cerr << errno << " " << strerror(errno) << endl;
            break;
        }
        else
        {
            cerr << "read error" << strerror(errno) << endl;
            break;
        }

    }

    close(sock);
    return 0;
}